/*
 * @Author: viivLgr 
 * @Date: 2018-05-29 17:45:24 
 * @Last Modified by: viivLgr
 * @Last Modified time: 2018-06-04 18:02:48
 */

class Util {
    request(param) {
        const _this = this;
        return new Promise((resolve, rejects) => {
            $.ajax({
                type: param.type || 'GET',
                url: param.url || '',
                dataType: param.dataType || 'json',
                data: param.data || null,
                success: res => {
                    if (0 === res.status) {
                        typeof resolve === 'function' && resolve(res.data, res.msg);
                    } else if (10 === res.status) {
                        // 登录
                        _this.doLogin();
                    } else {
                        typeof rejects === 'function' && rejects(res.msg || res.data);
                    }
                },
                error: err => {
                    rejects(err.statusText);
                }
            })
        })
    }
    // 跳转登录
    doLogin() {
        window.location.href = '/login?redirect=' + encodeURIComponent(window.location.pathname);
    }
    // 获取url参数
    getUrlParam(name) {
        let queryString = window.location.search.split('?')[1] || '',
            reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"),
            result = queryString.match(reg);
        return result ? decodeURIComponent(result[2]) : null;
    }
    // 成功提示
    successTips(msg) {
        alert(msg || '操作成功！');
    }
    // 错误提示
    errorTips(msg) {
        alert(msg || '好像哪里不对了~');
    }
    // 本地存储
    setStorage(name, data) {
        let dataType = typeof data;
        // json
        if (dataType === 'object') {
            window.localStorage.setItem(name, JSON.stringify(data));
        }
        // 基础类型
        else if (['number', 'string', 'boolean'].indexOf(dataType) >= 0) {
            window.localStorage.setItem(name, data);
        }
        else {
            this.errorTips('该类型不能用于本地存储');
        }
    }
    // 取出本地存储内容
    getStorage(name) {
        let data = window.localStorage.getItem(name);
        return data ? JSON.parse(data) : '';
    }
    // 删除本地存储
    removeStorage(name) {
        window.localStorage.removeItem(name);
    }
}

export default Util;
